package com.amigoscode.demo.student;

import com.amigoscode.demo.student.exception.BadRequestException;
import com.amigoscode.demo.student.exception.StudentNotFoundException;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.List;

@AllArgsConstructor
@Service
public class StudentService {
    private final StudentRepository studentRepository;

    public List<Student> getAllStudents() {
//        throw new IllegalStateException("oops error");
        return studentRepository.findAll();
    }

    public void addStudent(Student student) {
        // check if email is taken
//        if (studentRepository.exists(Example.of(student))) {
//            throw new IllegalStateException("email " + student.getEmail() + " was taken");
//        }
        Boolean existsEmail = studentRepository
                .selectExistsEmail(student.getEmail());
        if (existsEmail) {
            throw new BadRequestException("email " + student.getEmail() + " was taken");
        }
        studentRepository.save(student);
    }

    public void deleteStudent(Long studentId) {
        // check if student exists
//        Optional<Student> student = studentRepository.findById(studentId);
//        if (!student.isPresent()) {
//            throw new IllegalStateException("student with " + studentId + " does not exist");
//        }
        if (!studentRepository.existsById(studentId)) {
            throw new StudentNotFoundException("Student with id " + studentId + " does not exist");
        }
        studentRepository.deleteById(studentId);
    }
}
